package com.ali.stock.controller;

import com.ali.stock.config.R;
import com.ali.stock.domain.*;
import com.ali.stock.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("stock")
@Api(tags = "撮合交易-股票")//描
public class StockController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysStockService sysStockService;

    @Autowired
    SysEntrustService sysEntrustService;

    @Autowired
    SysEntrustUserService sysEntrustUserService;

    @Autowired
    SysUserStockService sysUserStockService;

    @Autowired
    SysDealService sysDealService;

    @Autowired
    SysUserDealService sysUserDealService;


    /**
     * 获得当前用户拥有的股票列表
     *
     * @param sysUser
     * @return
     */
    @ApiOperation(value="查询接口",notes = "获得当前用户拥有的股票列表")
    @PostMapping("getStockByList")
    public R getStockByList(@RequestBody SysUser sysUser) {
        PageHelper.startPage(sysUser.getPageNum(), sysUser.getPageSize());
        List<SysStock> sysStockList = sysStockService.getStockByUser(Math.toIntExact(sysUser.getUserId()));
        PageInfo pageInfo = new PageInfo<>(sysStockList);
        return R.successed(pageInfo);
    }

    /**
     * 获得当前用户的可用资金
     *
     * @param userId
     * @return
     */
    @GetMapping("getUserMoney")
    public R getUserMoney(Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        SysUser one = sysUserService.getOne(queryWrapper);
        return R.successed(one.getUserMoney());
    }

    /**
     * 添加委托
     */
    @PostMapping("saveEntrust1")
    public R saveEntrust(@RequestBody SysEntrust sysEntrust) {
        sysEntrust.setEntrustTime(new Date());
        boolean b = sysEntrustService.save(sysEntrust);
        //存储用户-委托中间表
        SysEntrustUser sysEntrustUser = new SysEntrustUser();
        sysEntrustUser.setUserId(sysEntrust.getHaveId());
        sysEntrustUser.setEntrustId(sysEntrust.getEntrustId());
        sysEntrustUserService.save(sysEntrustUser);
        //如果是买入的话需要扣除预付款
        if (sysEntrust.getEntrustDirection().equals("买入")) {
            //并且需要扣去预付款
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", sysEntrust.getHaveId());
            SysUser sysUser = sysUserService.getOne(queryWrapper);
            BigDecimal decimal = sysEntrust.getEntrustPrice().multiply(new BigDecimal(sysEntrust.getEntrustNum()));
            sysUser.setUserMoney(sysUser.getUserMoney().subtract(decimal));
            sysUserService.updateById(sysUser);
        }
        //如果是卖出的话需要扣除预卖数量
        if (sysEntrust.getEntrustDirection().equals("卖出")) {
            //获取股票对象
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("stock_no", sysEntrust.getEntrustStockCode());
            SysStock sysStock = sysStockService.getOne(queryWrapper);
            //获取用户-股票中间表信息并做修改
            QueryWrapper queryWrapper1 = new QueryWrapper<>()
                    .eq("stock_id", sysStock.getStockId())
                    .eq("user_id", sysEntrust.getHaveId());
            SysUserStock sysUserStock = sysUserStockService.getOne(queryWrapper1);
            //扣除要卖出的数量
            sysUserStock.setUserStockCount(sysUserStock.getUserStockCount() - sysEntrust.getEntrustNum());
            sysUserStockService.updateObject(sysUserStock);
        }
        return b == true ? R.successed(null) : R.failed("添加委任失败");
    }

    /**
     * 撮合交易————添加委托
     */
    @PostMapping("saveEntrust")
    public R saveEntustTest(@RequestBody SysEntrust sysEntrustinfo) {
        Integer entrustNum = sysEntrustinfo.getEntrustNum();
        BigDecimal sum = sysEntrustinfo.getEntrustPrice().multiply(new BigDecimal(entrustNum));
        Integer userINfoId = sysEntrustinfo.getHaveId();
        //先将所有的委托列表，分为卖家列表和买家列表
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("entrust_status", "已报");
        queryWrapper.eq("del_flag", 0);
        //所有能够交易股票的委托列表
        List<SysEntrust> sysAllEntrustList = sysEntrustService.list(queryWrapper);
        //买家的委托列表
        List<SysEntrust> buyEntrustList = new ArrayList<>();
        //卖家的委托列表
        List<SysEntrust> sellEntrustList = new ArrayList<>();
        for (SysEntrust entrust : sysAllEntrustList) {
            if (entrust.getEntrustDirection().equals("买入")) {
                buyEntrustList.add(entrust);
            } else {
                sellEntrustList.add(entrust);
            }
        }
        //交易之前先判断是卖家还是卖家
        if (sysEntrustinfo.getEntrustDirection().equals("买入")) {
            // todo 如果是买家,先查询卖家的列表中是否有股票符合条件
            // todo 价格和股票编号符合条件
            //判断可交易的数据是否一致，只交易能够交易的股票
            //保存交易成功的的信息到交易表中，（包括卖家、买家）
            //包括相应的关系表
            //买家的可用资金减少，保存到委托单中
            //买家的所拥有的股票是否有相同编号
            //如果有，则修改这支股票的总价值、股票个数，单价
            //如果没有，正常记录即可
            //卖家的可用资金增加，委托的订单状态修改，
            for (SysEntrust entrust : sellEntrustList) {
                if (entrust.getEntrustStockCode().equals(sysEntrustinfo.getEntrustStockCode())//股票编号相等
                        && sysEntrustinfo.getEntrustNum() != 0//仍在求购
                        && entrust.getEntrustPrice().compareTo(sysEntrustinfo.getEntrustPrice()) == 0) {//股票价格相等
                    //判卷买家和卖家的售卖数量是否一致
                    if (sysEntrustinfo.getEntrustNum() == entrust.getEntrustNum()) {
                        //双方的数量一致发
                        //调整卖家信息
                        QueryWrapper queryWrapper1 = new QueryWrapper();
                        queryWrapper1.eq("entrust_id", entrust.getEntrustId());
                        SysEntrustUser one = sysEntrustUserService.getOne(queryWrapper1);
                        //获得卖家用户ID
                        Integer sellUserId = one.getUserId();
                        //修改卖家委托单中的状态（从卖家列表中下架）
                        entrust.setEntrustStatus("已售出");
                        sysEntrustService.updateById(entrust);
                        //保存交易信息
                        SysDeal sysDeal = new SysDeal();
                        sysDeal.setDealTime(new Date());
                        sysDeal.setStoclName(entrust.getEntrustBankName());
                        sysDeal.setStockCode(entrust.getEntrustStockCode());
                        sysDeal.setDealPrice(entrust.getEntrustPrice());
                        sysDeal.setDealNum(entrust.getEntrustNum());
                        sysDeal.setDealMoney(entrust.getEntrustPrice().multiply(new BigDecimal(entrust.getEntrustNum())));
                        sysDeal.setDirection("售出");
                        sysDealService.save(sysDeal);
                        //保存卖家的用户-交易表信息
                        SysUserDeal sysUserDeal = new SysUserDeal();
                        sysUserDeal.setDealId(sysDeal.getDealId());
                        sysUserDeal.setUserId(sellUserId);
                        //修改卖家的可用资金（余额）
                        QueryWrapper queryWrapper2 = new QueryWrapper();
                        queryWrapper2.eq("user_id", sellUserId);
                        SysUser sellUser = sysUserService.getOne(queryWrapper2);
                        sellUser.setUserMoney(sellUser.getUserMoney().add(sysDeal.getDealMoney()));
                        sysUserService.updateById(sellUser);

                        //调整买家信息
                        //保存买家委托表信息
                        entrust.setEntrustId(null);
                        entrust.setEntrustTime(new Date());
                        entrust.setEntrustNum(entrustNum);
                        entrust.setEntrustDirection("买入");
                        entrust.setEntrustStatus("已购入");
                        sysEntrustService.save(entrust);
                        //保存买家 用户-委托关系表信息
                        SysEntrustUser sysEntrustUser = new SysEntrustUser();
                        sysEntrustUser.setEntrustId(entrust.getEntrustId());
                        sysEntrustUser.setUserId(userINfoId);
                        sysEntrustUserService.save(sysEntrustUser);
                        //保存买家交易表信息
                        SysDeal sysDeal1 = new SysDeal();
                        sysDeal1.setDealTime(new Date());
                        sysDeal1.setStockCode(entrust.getEntrustStockCode());
                        sysDeal1.setStoclName(entrust.getEntrustBankName());
                        sysDeal1.setDealPrice(entrust.getEntrustPrice());
                        sysDeal1.setDealNum(entrustNum);
                        sysDeal1.setDealMoney(sum);
                        sysDeal1.setDirection("购入");
                        sysDealService.save(sysDeal1);
                        //保存买家 用户-交易中间表信息
                        SysUserDeal sysUserDeal1 = new SysUserDeal();
                        sysUserDeal1.setDealId(sysDeal1.getDealId());
                        sysUserDeal1.setUserId(sysEntrustinfo.getHaveId());
                        sysUserDealService.save(sysUserDeal1);
                        //修改买家余额
                        QueryWrapper queryWrapper3 = new QueryWrapper();
                        queryWrapper3.eq("user_id", sysEntrustinfo.getHaveId());
                        SysUser buyUser = sysUserService.getOne(queryWrapper3);
                        buyUser.setUserMoney(buyUser.getUserMoney().subtract(sum));
                        sysUserService.updateById(buyUser);
                        //修改买家的拥有的股票数
                        QueryWrapper queryWrapper4 = new QueryWrapper();
                        queryWrapper4.eq("stock_no", sysEntrustinfo.getEntrustStockCode());
                        SysStock buyStock = sysStockService.getOne(queryWrapper4);
                        QueryWrapper queryWrapper5 = new QueryWrapper();
                        queryWrapper5.eq("stock_id", buyStock.getStockId());
                        queryWrapper5.eq("user_id", userINfoId);
                        SysUserStock buySysUserStock = sysUserStockService.getOne(queryWrapper5);
                        buySysUserStock.setUserStockCount(buySysUserStock.getUserStockCount() + entrustNum);
                        sysUserStockService.updateObject(buySysUserStock);

                        String message = sysEntrustinfo.getHaveId() + ",恭喜您成功购入名为：" + sysEntrustinfo.getEntrustBankName()
                                + "的股票，数量为" + entrustNum;
                        //最后将买家的求购数量置空
                        sysEntrustinfo.setPageNum(0);
                        return R.successed(message);
                    } else {
                        //双发的数量不一致,则判断卖家数量大，还是买家数量大
                        if (entrust.getEntrustNum() > sysEntrustinfo.getEntrustNum()) {
                            //卖家数量大
                            //调整卖家信息
                            QueryWrapper queryWrapper1 = new QueryWrapper();
                            queryWrapper1.eq("entrust_id", entrust.getEntrustId());
                            SysEntrustUser one = sysEntrustUserService.getOne(queryWrapper1);
                            //获得卖家用户ID
                            Integer sellUserId = one.getUserId();
                            Integer entrustNumSum = entrust.getEntrustNum();
                            //修改卖家委托单中的状态（从卖家列表中下架）
                            entrust.setEntrustNum(entrustNum);
                            entrust.setEntrustStatus("部分售出");
                            sysEntrustService.updateById(entrust);
                            //将剩下的股票继续交由委托，等待交易
                            entrust.setEntrustId(null);
                            entrust.setEntrustNum(entrustNumSum - entrust.getEntrustNum());
                            entrust.setEntrustStatus("卖出");
                            sysEntrustService.save(entrust);
                            //新增用户和委托关系表
                            SysEntrustUser sysEntrustUser1 = new SysEntrustUser();
                            sysEntrustUser1.setUserId(sellUserId);
                            sysEntrustUser1.setEntrustId(entrust.getEntrustId());
                            sysEntrustUserService.save(sysEntrustUser1);
                            //保存交易信息
                            SysDeal sysDeal = new SysDeal();
                            sysDeal.setDealTime(new Date());
                            sysDeal.setStoclName(entrust.getEntrustBankName());
                            sysDeal.setStockCode(entrust.getEntrustStockCode());
                            sysDeal.setDealPrice(entrust.getEntrustPrice());
                            sysDeal.setDealNum(entrustNum);
                            sysDeal.setDealMoney(sum);
                            sysDeal.setDirection("售出");
                            sysDealService.save(sysDeal);
                            //保存卖家的用户-交易表信息
                            SysUserDeal sysUserDeal = new SysUserDeal();
                            sysUserDeal.setDealId(sysDeal.getDealId());
                            sysUserDeal.setUserId(sellUserId);
                            //修改卖家的可用资金（余额）
                            QueryWrapper queryWrapper2 = new QueryWrapper();
                            queryWrapper2.eq("user_id", sellUserId);
                            SysUser sellUser = sysUserService.getOne(queryWrapper2);
                            sellUser.setUserMoney(sellUser.getUserMoney().add(sysDeal.getDealMoney()));
                            sysUserService.updateById(sellUser);


                            //调整买家信息
                            //保存买家委托表信息
                            entrust.setEntrustId(null);
                            entrust.setEntrustTime(new Date());
                            entrust.setEntrustNum(entrustNum);
                            entrust.setEntrustDirection("买入");
                            entrust.setEntrustStatus("已购入");
                            sysEntrustService.save(entrust);
                            //保存买家 用户-委托关系表信息
                            SysEntrustUser sysEntrustUser = new SysEntrustUser();
                            sysEntrustUser.setEntrustId(entrust.getEntrustId());
                            sysEntrustUser.setUserId(userINfoId);
                            sysEntrustUserService.save(sysEntrustUser);
                            //保存买家交易表信息
                            SysDeal sysDeal1 = new SysDeal();
                            sysDeal1.setDealTime(new Date());
                            sysDeal1.setStockCode(entrust.getEntrustStockCode());
                            sysDeal1.setStoclName(entrust.getEntrustBankName());
                            sysDeal1.setDealPrice(entrust.getEntrustPrice());
                            sysDeal1.setDealNum(entrustNum);
                            sysDeal1.setDealMoney(sum);
                            sysDeal1.setDirection("购入");
                            sysDealService.save(sysDeal1);
                            //保存买家 用户-交易中间表信息
                            SysUserDeal sysUserDeal1 = new SysUserDeal();
                            sysUserDeal1.setDealId(sysDeal1.getDealId());
                            sysUserDeal1.setUserId(sysEntrustinfo.getHaveId());
                            sysUserDealService.save(sysUserDeal1);
                            QueryWrapper queryWrapper3 = new QueryWrapper();
                            //修改买家可用资金（余额）
                            queryWrapper3.eq("user_id", sysEntrustinfo.getHaveId());
                            SysUser buyUser = sysUserService.getOne(queryWrapper3);
                            buyUser.setUserMoney(buyUser.getUserMoney().subtract(sum));
                            sysUserService.updateById(buyUser);
                            //修改买家的拥有的股票数
                            QueryWrapper queryWrapper4 = new QueryWrapper();
                            queryWrapper4.eq("stock_no", sysEntrustinfo.getEntrustStockCode());
                            SysStock buyStock = sysStockService.getOne(queryWrapper4);
                            QueryWrapper queryWrapper5 = new QueryWrapper();
                            queryWrapper5.eq("stock_id", buyStock.getStockId());
                            queryWrapper5.eq("user_id", userINfoId);
                            SysUserStock buySysUserStock = sysUserStockService.getOne(queryWrapper5);
                            buySysUserStock.setUserStockCount(buySysUserStock.getUserStockCount() + entrustNum);
                            sysUserStockService.updateObject(buySysUserStock);

                            String message = sysEntrustinfo.getHaveId() + ",恭喜您成功购入名为：" + sysEntrustinfo.getEntrustBankName()
                                    + "的股票，数量为" + entrustNum;
                            //最后将买家的求购数量置空
                            sysEntrustinfo.setPageNum(0);
                            return R.successed(message);

                        } else {
                            //买家数量大
                            //调整卖家信息
                            QueryWrapper queryWrapper1 = new QueryWrapper();
                            queryWrapper1.eq("entrust_id", entrust.getEntrustId());
                            SysEntrustUser one = sysEntrustUserService.getOne(queryWrapper1);
                            //获得卖家用户ID
                            Integer sellUserId = one.getUserId();
                            //修改卖家委托单中的状态（从卖家列表中下架）
                            entrust.setEntrustStatus("已售出");
                            sysEntrustService.updateById(entrust);
                            //保存交易信息
                            SysDeal sysDeal = new SysDeal();
                            sysDeal.setDealTime(new Date());
                            sysDeal.setStoclName(entrust.getEntrustBankName());
                            sysDeal.setStockCode(entrust.getEntrustStockCode());
                            sysDeal.setDealPrice(entrust.getEntrustPrice());
                            sysDeal.setDealNum(entrust.getEntrustNum());
                            sysDeal.setDealMoney(entrust.getEntrustPrice().multiply(new BigDecimal(entrust.getEntrustNum())));
                            sysDeal.setDirection("售出");
                            sysDealService.save(sysDeal);
                            //保存卖家的用户-交易表信息
                            SysUserDeal sysUserDeal = new SysUserDeal();
                            sysUserDeal.setDealId(sysDeal.getDealId());
                            sysUserDeal.setUserId(sellUserId);
                            //修改卖家的可用资金（余额）
                            QueryWrapper queryWrapper2 = new QueryWrapper();
                            queryWrapper2.eq("user_id", sellUserId);
                            SysUser sellUser = sysUserService.getOne(queryWrapper2);
                            sellUser.setUserMoney(sellUser.getUserMoney().add(sysDeal.getDealMoney()));
                            sysUserService.updateById(sellUser);

                            //调整买家信息
                            sysEntrustinfo.setEntrustNum(sysEntrustinfo.getEntrustNum() - entrust.getEntrustNum());
                        }
                    }

                }
            }
            // todo 如果是买家,卖家的价格和股票编号不符合条件，则考虑买家列表
            //判断买家委托列表中是否拥有自己的股票
            //同一支的相同价格，则修改委托表中的信息即可
            //没有自己提交相同的股票，则正常添加即可
            // 添加信息到买家委托表，买家可用资金减少
            //包括相应的关系表

            String message = "";
            //判断是否成交了一部分
            if (entrustNum != sysEntrustinfo.getEntrustNum()) {
                //调整买家信息
                //保存买家委托表信息
                sysEntrustinfo.setEntrustId(null);
                SysEntrust sysEntrust = sysEntrustinfo;
                sysEntrust.setEntrustTime(new Date());
                sysEntrust.setEntrustNum(entrustNum - sysEntrustinfo.getEntrustNum());
                sysEntrust.setEntrustTime(new Date());
                sysEntrust.setEntrustStatus("已购入");
                sysEntrustService.save(sysEntrustinfo);
                //保存买家 用户-委托关系表信息
                SysEntrustUser sysEntrustUser = new SysEntrustUser();
                sysEntrustUser.setEntrustId(sysEntrustinfo.getEntrustId());
                sysEntrustUser.setUserId(userINfoId);
                sysEntrustUserService.save(sysEntrustUser);
                //保存买家交易表信息
                SysDeal sysDeal1 = new SysDeal();
                sysDeal1.setDealTime(new Date());
                sysDeal1.setStockCode(sysEntrustinfo.getEntrustStockCode());
                sysDeal1.setStoclName(sysEntrustinfo.getEntrustBankName());
                sysDeal1.setDealPrice(sysEntrustinfo.getEntrustPrice());
                sysDeal1.setDealNum(sysEntrustinfo.getEntrustNum());
                sysDeal1.setDealMoney(sysEntrustinfo.getEntrustPrice().multiply(new BigDecimal(sysEntrustinfo.getEntrustNum())));
                sysDeal1.setDirection("购入");
                sysDealService.save(sysDeal1);
                //保存买家 用户-交易中间表信息
                SysUserDeal sysUserDeal1 = new SysUserDeal();
                sysUserDeal1.setDealId(sysDeal1.getDealId());
                sysUserDeal1.setUserId(sysEntrustinfo.getHaveId());
                sysUserDealService.save(sysUserDeal1);
                QueryWrapper queryWrapper3 = new QueryWrapper();
                //修改买家可用资金（余额）
                queryWrapper3.eq("user_id", sysEntrustinfo.getHaveId());
                SysUser buyUser = sysUserService.getOne(queryWrapper3);
                buyUser.setUserMoney(buyUser.getUserMoney().subtract(sum));
                sysUserService.updateById(buyUser);
                sysEntrustinfo.setEntrustId(null);
                message = sysEntrustinfo.getHaveId() + ",恭喜您成功购入名为：" + sysEntrustinfo.getEntrustBankName()
                        + "的股票，数量为" + (entrustNum - sysEntrustinfo.getEntrustNum());

            }

            for (SysEntrust sysEntrust : buyEntrustList) {
                if (sysEntrust.getEntrustStockCode().equals(sysEntrustinfo.getEntrustStockCode())
                        && sysEntrust.getEntrustPrice().equals(sysEntrustinfo.getEntrustPrice())) {
                    sysEntrust.setEntrustNum(sysEntrust.getEntrustNum() + sysEntrustinfo.getEntrustNum());
                    sysEntrustService.updateById(sysEntrust);
                    return R.successed(message);
                }
            }
            sysEntrustinfo.setEntrustId(null);
            sysEntrustinfo.setEntrustTime(new Date());
            sysEntrustService.save(sysEntrustinfo);
            SysEntrustUser sysEntrustUser = new SysEntrustUser();
            sysEntrustUser.setEntrustId(sysEntrustinfo.getEntrustId());
            sysEntrustUser.setUserId(userINfoId);
            sysEntrustUserService.save(sysEntrustUser);
            return R.successed(message);
        } else {
            // todo 如果是卖家，先查询买家的列表中是否有股票符合条件
            // todo 价格和股票符合卖家条件
            //判断可交易的数据是否一致，只交易能够交易的股票
            //保存交易成功的信息到交易表中，（包括卖家、买家）以及关系表
            //保存委托的信息/修改委托的信息，（包括卖家、买家）
            //修改卖家的可用资金（增加）
            //判断买家是否持有这支股票
            //修改对应股票中的单价、以及中间表中的股票数量
            //如果没有，正常添加股票即可，
            for (SysEntrust sysEntrust : buyEntrustList) {
                //判断卖家的价格与买家相同
                if (sysEntrust.getEntrustPrice().compareTo(sysEntrustinfo.getEntrustPrice()) == 0
                        //卖家的购买数量不能为0
                        && sysEntrustinfo.getEntrustNum() != 0
                        //卖家的股票号与买家相同
                        && sysEntrust.getEntrustStockCode().equals(sysEntrustinfo.getEntrustStockCode())) {
                    //卖家的股票数量与买家相同或者小于
                    if (sysEntrust.getEntrustNum() <= sysEntrustinfo.getEntrustNum()) {
                        //先处理买家信息
                        //获得买家用户ID
                        QueryWrapper queryWrapper3 = new QueryWrapper();
                        queryWrapper3.eq("entrust_id", sysEntrust.getEntrustId());
                        SysEntrustUser one = sysEntrustUserService.getOne(queryWrapper3);
                        Integer buyUserId = one.getUserId();
                        //判断买家的股票数量是否大于卖家
                        if (sysEntrust.getEntrustNum() > sysEntrustinfo.getEntrustNum()) {
                            //将原有的委托单修改
                            sysEntrust.setEntrustNum(sysEntrust.getEntrustNum() - entrustNum);
                            sysEntrustService.updateById(sysEntrust);
                            //保存
                            sysEntrust.setEntrustId(null);
                            sysEntrust.setEntrustNum(entrustNum);
                            sysEntrust.setEntrustStatus("部分购入");
                            sysEntrust.setEntrustTime(new Date());
                            sysEntrustService.save(sysEntrust);
                            SysEntrustUser buyEntrustUser = new SysEntrustUser();
                            buyEntrustUser.setUserId(buyUserId);
                            buyEntrustUser.setEntrustId(sysEntrust.getEntrustId());
                            sysEntrustUserService.save(buyEntrustUser);
                        } else {
                            //将原有的委托单修改
                            sysEntrust.setEntrustNum(entrustNum);
                            sysEntrust.setEntrustStatus("已购入");
                            sysEntrustService.updateById(sysEntrust);
                        }
                        //添加买家交易信息
                        SysDeal buyDeal = new SysDeal();
                        buyDeal.setStoclName(sysEntrust.getEntrustBankName());
                        buyDeal.setStockCode(sysEntrust.getEntrustStockCode());
                        buyDeal.setDealTime(new Date());
                        buyDeal.setDealPrice(sysEntrust.getEntrustPrice());
                        buyDeal.setDealMoney(sum);
                        buyDeal.setDealNum(entrustNum);
                        buyDeal.setDirection("已购入");
                        sysDealService.save(buyDeal);
                        //添加买家用户-交易关系表
                        SysUserDeal buyUserDeal = new SysUserDeal();
                        buyUserDeal.setUserId(buyUserId);
                        buyUserDeal.setDealId(buyDeal.getDealId());
                        sysUserDealService.save(buyUserDeal);
                        //修改买家的股票数量
                        QueryWrapper queryWrapper5 = new QueryWrapper();
                        queryWrapper5.eq("stock_no", buyDeal.getStockCode());
                        SysStock buyStock = sysStockService.getOne(queryWrapper5);
                        QueryWrapper queryWrapper14 = new QueryWrapper();
                        queryWrapper14.eq("stock_id", buyStock.getStockId());
                        queryWrapper14.eq("user_id", buyUserId);
                        SysUserStock buyUserStock = sysUserStockService.getOne(queryWrapper14);
                        buyUserStock.setUserStockCount(buyUserStock.getUserStockCount() - entrustNum);
                        sysUserStockService.updateObject(buyUserStock);

                        //处理卖家信息
                        //先保存卖家委托信息
                        sysEntrustinfo.setEntrustId(null);
                        sysEntrustinfo.setEntrustStatus("已售出");
                        sysEntrustinfo.setEntrustTime(new Date());
                        sysEntrustService.save(sysEntrustinfo);
                        //保存卖家的用户和委托关系表
                        SysEntrustUser sellEntrustUser = new SysEntrustUser();
                        sellEntrustUser.setEntrustId(sysEntrustinfo.getEntrustId());
                        sellEntrustUser.setUserId(userINfoId);
                        sysEntrustUserService.save(sellEntrustUser);
                        //保存卖家交易表
                        SysDeal sellDeal = new SysDeal();
                        sellDeal.setStoclName(sysEntrustinfo.getEntrustBankName());
                        sellDeal.setDealTime(new Date());
                        sellDeal.setStockCode(sysEntrustinfo.getEntrustStockCode());
                        sellDeal.setDealPrice(sysEntrustinfo.getEntrustPrice());
                        sellDeal.setDealNum(entrustNum);
                        sellDeal.setDealMoney(sum);
                        sellDeal.setDirection("售出");
                        sysDealService.save(sellDeal);
                        //保存卖家交易-用户关系表
                        SysUserDeal sellUserDeal = new SysUserDeal();
                        sellUserDeal.setDealId(sellDeal.getDealId());
                        sellUserDeal.setUserId(userINfoId);
                        sysUserDealService.save(sellUserDeal);
                        //修改股票数量
                        QueryWrapper queryWrapper1 = new QueryWrapper();
                        queryWrapper1.eq("stock_no", sellDeal.getStockCode());
                        SysStock sellStock = sysStockService.getOne(queryWrapper1);
                        QueryWrapper queryWrapper2 = new QueryWrapper();
                        queryWrapper2.eq("stock_id", sellStock.getStockId());
                        queryWrapper2.eq("user_id", userINfoId);
                        SysUserStock sellUserStock = sysUserStockService.getOne(queryWrapper2);
                        sellUserStock.setUserStockCount(sellUserStock.getUserStockCount() - entrustNum);
                        sysUserStockService.updateObject(sellUserStock);
                        //修改卖家可用资金
                        SysUser sellUserServiceById = sysUserService.getById(userINfoId);
                        sellUserServiceById.setUserMoney(sellUserServiceById.getUserMoney().add(sum));
                        sysUserService.updateById(sellUserServiceById);
                        sysEntrustinfo.setEntrustNum(0);

                        String message = sysEntrustinfo.getHaveId() + ",恭喜您成功售出名为：" + sysEntrustinfo.getEntrustBankName()
                                + "的股票，数量为" + (entrustNum);
                        return R.successed(message);
                    } else {
                        //卖家售卖的股票小于买家的股票数量
                        QueryWrapper queryWrapper3 = new QueryWrapper();
                        queryWrapper3.eq("entrust_id", sysEntrust.getEntrustId());
                        SysEntrustUser one = sysEntrustUserService.getOne(queryWrapper3);
                        Integer buyUserId = one.getUserId();
                        //将原有的委托单修改
                        sysEntrust.setEntrustStatus("已购入");
                        sysEntrustService.updateById(sysEntrust);
                        //添加买家交易信息
                        SysDeal buyDeal = new SysDeal();
                        buyDeal.setStoclName(sysEntrust.getEntrustBankName());
                        buyDeal.setStockCode(sysEntrust.getEntrustStockCode());
                        buyDeal.setDealTime(new Date());
                        buyDeal.setDealPrice(sysEntrust.getEntrustPrice());
                        buyDeal.setDealMoney(sysEntrust.getEntrustPrice().multiply(new BigDecimal(sysEntrust.getEntrustNum())));
                        buyDeal.setDealNum(sysEntrust.getEntrustNum());
                        buyDeal.setDirection("已购入");
                        sysDealService.save(buyDeal);
                        //添加买家用户-交易关系表
                        SysUserDeal buyUserDeal = new SysUserDeal();
                        buyUserDeal.setUserId(buyUserId);
                        buyUserDeal.setDealId(buyDeal.getDealId());
                        sysUserDealService.save(buyUserDeal);
                        //修改买家的股票数量
                        QueryWrapper queryWrapper5 = new QueryWrapper();
                        queryWrapper5.eq("stock_no", buyDeal.getStockCode());
                        SysStock buyStock = sysStockService.getOne(queryWrapper5);
                        QueryWrapper queryWrapper4 = new QueryWrapper();
                        queryWrapper4.eq("stock_id", buyStock.getStockId());
                        queryWrapper4.eq("user_id", buyUserId);
                        SysUserStock buyUserStock = sysUserStockService.getOne(queryWrapper4);
                        buyUserStock.setUserStockCount(buyUserStock.getUserStockCount() + sysEntrust.getEntrustNum());
                        sysUserStockService.updateObject(buyUserStock);

                        sysEntrustinfo.setEntrustNum(sysEntrustinfo.getEntrustNum() - sysEntrust.getEntrustNum());
                    }

                }
            }

            // todo 价格和股票不符合卖家条件，则考虑卖家列表
            //判断是否有自己已提交的委托单，
            //如果编号和价格相同，则修改数量即可
            //如果没有则正常调加委托表
            // 添加信息到卖家的委托表，卖家的股票数量改变
            //包括相应的关系表
            String message = "";
            //判断是否成交了一部分
            if (entrustNum != sysEntrustinfo.getEntrustNum()) {
                //调整卖家信息
                //保存卖家委托表信息
                sysEntrustinfo.setEntrustId(null);
                SysEntrust sysEntrust = sysEntrustinfo;
                sysEntrust.setEntrustTime(new Date());
                sysEntrust.setEntrustNum(entrustNum - sysEntrustinfo.getEntrustNum());
                sysEntrust.setEntrustTime(new Date());
                sysEntrust.setEntrustStatus("已售出");
                sysEntrustService.save(sysEntrustinfo);
                //保存卖家 用户-委托关系表信息
                SysEntrustUser sysEntrustUser = new SysEntrustUser();
                sysEntrustUser.setEntrustId(sysEntrustinfo.getEntrustId());
                sysEntrustUser.setUserId(userINfoId);
                sysEntrustUserService.save(sysEntrustUser);
                //保存卖家交易表信息
                SysDeal sysDeal1 = new SysDeal();
                sysDeal1.setDealTime(new Date());
                sysDeal1.setStockCode(sysEntrustinfo.getEntrustStockCode());
                sysDeal1.setStoclName(sysEntrustinfo.getEntrustBankName());
                sysDeal1.setDealPrice(sysEntrustinfo.getEntrustPrice());
                sysDeal1.setDealNum(sysEntrustinfo.getEntrustNum());
                sysDeal1.setDealMoney(sysEntrustinfo.getEntrustPrice().multiply(new BigDecimal(sysEntrustinfo.getEntrustNum())));
                sysDeal1.setDirection("售出");
                sysDealService.save(sysDeal1);
                //保存买家 用户-交易中间表信息
                SysUserDeal sysUserDeal1 = new SysUserDeal();
                sysUserDeal1.setDealId(sysDeal1.getDealId());
                sysUserDeal1.setUserId(sysEntrustinfo.getHaveId());
                sysUserDealService.save(sysUserDeal1);
                QueryWrapper queryWrapper3 = new QueryWrapper();
                //修改卖家股票数量
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("stock_no", sysEntrustinfo.getEntrustStockCode());
                SysStock one = sysStockService.getOne(queryWrapper);
                QueryWrapper queryWrapper2 = new QueryWrapper();
                queryWrapper2.eq("stock_id", one.getStockId());
                queryWrapper2.eq("user_id", userINfoId);
                SysUserStock sellUserStock = sysUserStockService.getOne(queryWrapper2);
                sellUserStock.setUserStockCount(sellUserStock.getUserStockCount() - entrustNum);
                sysUserStockService.updateObject(sellUserStock);
                sysEntrustinfo.setEntrustId(null);
                message = sysEntrustinfo.getHaveId() + ",恭喜您成功售出名为：" + sysEntrustinfo.getEntrustBankName()
                        + "的股票，数量为" + (entrustNum - sysEntrustinfo.getEntrustNum());

            }

            for (SysEntrust sysEntrust : sellEntrustList) {
                if (sysEntrust.getEntrustStockCode().equals(sysEntrustinfo.getEntrustStockCode())
                        && sysEntrust.getEntrustPrice().equals(sysEntrustinfo.getEntrustPrice())) {
                    sysEntrust.setEntrustNum(sysEntrust.getEntrustNum() + sysEntrustinfo.getEntrustNum());
                    sysEntrustService.updateById(sysEntrust);
                    return R.successed(message);
                }
            }
            sysEntrustinfo.setEntrustId(null);
            ;
            sysEntrustinfo.setEntrustTime(new Date());
            sysEntrustService.save(sysEntrustinfo);
            SysEntrustUser sysEntrustUser = new SysEntrustUser();
            sysEntrustUser.setUserId(userINfoId);
            sysEntrustUser.setEntrustId(sysEntrustinfo.getEntrustId());
            sysEntrustUserService.save(sysEntrustUser);
            return R.successed(message);
        }
    }

    /**
     * 撤单
     */
    @PostMapping("updateEntrustByStatus")
    public R updateEntrustByStatus(@RequestBody SysEntrust sysEntrust) {
        boolean b = sysEntrustService.updateById(sysEntrust);
        //只有买入需要退预付款
        if (sysEntrust.getEntrustDirection().equals("买入")) {
            //计算预付款
            BigDecimal multiply = sysEntrust.getEntrustPrice().multiply(new BigDecimal(sysEntrust.getEntrustNum()));
            //撤单之后需要将预付款退还账户
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", sysEntrust.getHaveId());
            SysUser sysUser = sysUserService.getOne(queryWrapper);
            sysUser.setUserMoney(sysUser.getUserMoney().add(multiply));
            sysUserService.updateById(sysUser);
        }
        //如果是卖出的话，预扣数量需要恢复
        if (sysEntrust.getEntrustDirection().equals("卖出")) {
            //获取具体的股票信息
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("stock_no", sysEntrust.getEntrustStockCode());
            SysStock sysStock = sysStockService.getOne(queryWrapper);
            //获得股票和用户的关系表并做修改
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("user_id", sysEntrust.getHaveId());
            queryWrapper1.eq("stock_id", sysStock.getStockId());
            SysUserStock sysUserStock = sysUserStockService.getOne(queryWrapper1);
            //加上委托扣除的数量
            sysUserStock.setUserStockCount(sysUserStock.getUserStockCount() + sysEntrust.getEntrustNum());
            sysUserStockService.updateObject(sysUserStock);
        }
        return b == true ? R.successed(null) : R.failed("撤单失败失败");
    }

    /**
     * 查看历史委托
     */
    @PostMapping("getHistoryEntrustList")
    public R getHistoryEntrustList(@RequestBody SysUser sysUser) {
        PageHelper.startPage(sysUser.getPageNum(), sysUser.getPageSize());
        List<SysEntrust> sysEntrustList = sysEntrustService.getHistoryEntrustList(sysUser.getUserId());
        PageInfo pageInfo = new PageInfo<>(sysEntrustList);
        return R.successed(pageInfo);
    }

    /**
     * 查看今日委托
     */
    @PostMapping("getTodayEntrustList")
    public R getTodayEntrustList(@RequestBody SysUser sysUser) {
        PageHelper.startPage(sysUser.getPageNum(), sysUser.getPageSize());
        List<SysEntrust> sysEntrustList = sysEntrustService.getTodayEntrustList(sysUser.getUserId());
        PageInfo pageInfo = new PageInfo<>(sysEntrustList);
        return R.successed(pageInfo);
    }

    /**
     * 获取最大选择数
     */
    @PostMapping("getMaxCount")
    public R getMaxCount(@RequestBody SysUser sysUser) {
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("user_id", sysUser.getUserId());
//        SysUser one = sysUserService.getOne(queryWrapper);
        LambdaQueryWrapper<SysUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserId,sysUser.getUserId());
        SysUser one = sysUserService.getOne(wrapper);
        BigDecimal userMoney = one.getUserMoney();
        //可用资金除以股票的单价（向下取证，保留0位小数）
        BigDecimal count = userMoney.divide(new BigDecimal(sysUser.getHaveId()), 0, RoundingMode.DOWN);
        return R.successed(count);
    }


    /**
     * 获取股票列表
     */
    @GetMapping("getStockList")
    public R getStockList() {
        List<SysStock> sysStockList = sysStockService.list();
        return R.successed(sysStockList);
    }

    /**
     * 获取当前用户历史成交的记录
     */
    @PostMapping("getHistoryDealList")
    public R getHistoryDealList(@RequestBody SysDeal sysDeal) {
        PageHelper.startPage(sysDeal.getPageNum(),sysDeal.getPageSize());
        List<SysDeal> sysDealList = sysDealService.getHistoryDealList(sysDeal);
        PageInfo pageInfo = new PageInfo<>(sysDealList);
        return R.successed(pageInfo);
    }

    /**
     * 获取当前用户今日的成交记录
     */
    @PostMapping("getTodayDealList")
    public R getTodayDealList(@RequestBody SysDeal sysDeal){
        PageHelper.startPage(sysDeal.getPageNum(),sysDeal.getPageSize());
        List<SysDeal> sysDealList = sysDealService.getTodayDealList(sysDeal);
        PageInfo pageInfo = new PageInfo<>(sysDealList);
        return R.successed(pageInfo);
    }


    /**
     * 获取股票的K线图数据
     */
    @GetMapping("getKByStockGid")
    public R getKByStockGid(Integer stockId){

        return R.successed(null);
    }


/**
 * 传统软件公司
 * 互联网公司
 * IT公司
 *
 *
 * 互联网管理的三驾马车
 * 产品
 * 1用户产品
 *    需求分析、
 *         商业需求分析
 *         市场需求分析
 *         产品需求分析
 *    产品实现、
 *          用户调研
 *          产品规划
 *          原型设计
 *          美工设计
 *          UI设计
 *
 *    产品检测
 *      用户粘性
 *      访问深度
 *      点击率
 *      跳出率
 *      活跃度
 *      注册率
 * 2商业策略
 * 3商业产品
 *
 *
 * 技术
 *
 *   1架构、
 *     整体价格设计
 *     数据中心
 *     数据库设计
 *     中间件设计
 *     协议制定
 *   2开发、
 *     接口制定
 *     编码
 *     单元测试
 *     持续集成
 *   3质量、
 *       质量测试
 *       安全测试
 *       性能测试
 *   4运维、
 *      服务器拓扑
 *      数据备份
 *      线上监控
 *      日志处理
 *
 * 运营
 *   编辑
 *      基础数据
 *      模拟用户
 *      内容更新
 *   策划
 *      品牌宣传
 *      活动策划
 *   推广引流
 *
 *   转化
 *     注册率
 *     购买率
 *
 * 组织结构
 *   中小型公司
 *      总裁办：
 *         总裁+VP
 *      技术中心：
 *          技术部
 *          测试部
 *          运维部
 *      运营中心
 *           产品部（用户产品部、商业产品部）
 *
 *
 *        《JAVA编程思想》 埃克尔
 *        《数据库系统概论》 王珊/萨师煊
 *        《数据结构》 严蔚敏-》邓俊辉
 *        《计算机网络（第5版）》 Andrew S.Tanenbaum
 *        《计算机组成与设计（第4版）》
 *        《计算机系统结构》张晨曦、王志英
 *        《操作系统》 William Stallings
 *        《机器学习》Mitchell TM.（米歇尔）
 */
}
